const tabbar = require("../../utils/tabbar");
const defaultAvatarUrl = '/pages/images/txa.png'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        videoInfo: '',
        showTosting: false,
        activ_int: 0,
        // 完善信息
        input_disable: false,
        name: '',
        telephone:'',
        company: '',
        duties: '',
        // 授权头像昵称
        show_disable: false,
        nickName: '', // 用户昵称
        avatarUrl: defaultAvatarUrl,
        showtos: false,  //弹出显示隐藏
        lo_gin: 0,
        user_login: false,
        times_flag: false,
        active: 0, // tab 选项卡
        currentTab: 0,  // tab 选项卡
        show: false, // 检索
        showTostat: false,
        opening: false,
        brief: {
            tile: '上海蜜度科技股份有限公司',
            url: 'https://www.midu.com',
            itbrief: '  蜜度创立于2009年，是一家以人工智能技术为核心的语言智能科技企业，专注于多模态、多语言智能科技，通过AI技术与智能应用赋能千行百业实现数字化、智能化转型升级。',
            img_url: '../images/md_bg.png',
        },
        personal: {
            id: 0,
            img_url: '', // 头像
            name: '-', //姓名
            career: '-', // 职业
            phone: '-', // 电话
            email: '-', // 邮箱
            addres: '-',  // 地址
            is_self: false,
        },
        video_list: [],
        visitor: [],
        cat_id: 0,
        cat_name: '',
        product: [],
        news_cat: [
            {
                id: 1,
                name: '最近',
            },
            {
                id: 2,
                name: '官方',
            },
        ],
        news: [],
        // 官方宣传手册
        manual: [],
        actions: [],
        focus: false,
        va_search: '',
    },
    showPopup() {
        this.setData({ showTosting: true });
    },

    onCloseert() {
        this.setData({ showTosting: false });
    },

    onCloserdat() {
        this.setData({ showTostat: false });
    },

    onChooseAvatar(e) {
        // const { avatarUrl } = e.detail
        // this.setData({
        // 	'loginInfo.avatarUrl': avatarUrl
        // })
        var that = this;
        const {
            avatarUrl
        } = e.detail;
        wx.getImageInfo({
            src: avatarUrl,
            success(res) {
                console.log(res);
                if (res.width !== res.height) { //如果不是正方形 进行裁剪工作
                    //微信裁剪接口（2.26.0 开始支持）
                    wx.cropImage({
                        src: avatarUrl, // 图片路径
                        cropScale: '1:1', // 裁剪比例
                        success(res) {

                            getApp().util.uploadfile(res.tempFilePath, {}).then((res) => {
                                let src = res.data.fullurl
                                console.log(src)
                                that.setData({
                                    avatarUrl: src,
                                });
                            })
                        },
                        fail: function (res) { },
                        complete: function (res) { }
                    })

                } else {
                    getApp().util.uploadfile(avatarUrl, {}).then((res) => {
                        let src = res.data.fullurl
                        that.setData({
                            avatarUrl: src,
                        });
                    })
                }
            },
            fail: function (res) { },
            complete: function (res) { }
        })
    },
    
    //授权手机号
    getPhoneNumber: function (e) {
        console.log(e);
        var that = this;
        if (e.detail.errMsg == "getPhoneNumber:ok") {
            var params = {}
            params.encryptedData = e.detail.encryptedData
            params.iv = e.detail.iv
            params.code = e.detail.code;

            getApp().util.request({
                url: 'user/get_mobile',
                data: params,
            }).then(function (res) {
                console.log(res)
                that.setData({
                    telephone: res.phone,
                    // isAgree: true
                })
            })
        }else{
            // wx.showToast({
            //   title: e.detail.errMsg,
            //   icon:'none'
            // });
        }
    },
    // 移动端
    webindex() {
        let flag = this.is_perfect();
        if (!flag) {
            return false;
        }
        let url = this.data.brief.url;
        wx.navigateTo({
            url: '/pages/progress/index?url=' + url,
        })
    },
    // 产品
    news_url() {
        console.log('123');
    },
    // 访客记录
    record() {
        wx.navigateTo({
            url: '/pages/record/record',
        })
    },
    // 拨打电话
    call: function () {
        wx.makePhoneCall({
            phoneNumber: this.data.personal.phone
        }).catch((e) => { });
    },
    // 保存到通讯录
    saveUserinfo() {
        wx.requirePrivacyAuthorize({
            success: res => {
                console.log(res)
                if (res.errMsg == "requirePrivacyAuthorize:ok") {
                    console.log('已同意')
                    wx.addPhoneContact({
                        lastName: this.data.personal.name, // 姓名
                        mobilePhoneNumber: this.data.personal.phone,  // 电话
                        email: this.data.personal.email, // 邮箱
                        title: this.data.personal.career, // 职位
                        // url: this.data.addres.wangzhan, // 公司网址
                        organization: this.data.personal.addres, // 公司地址
                        success: function (res) {
                            console.log('保存成功', res);
                        },
                        fail: function (res) {
                            console.log('失败', res.errMsg)
                            wx.getSetting().then(res => {
                                if (!res.authSetting['scope.addPhoneContact']) {
                                    wx.showModal({
                                        title: '授权提醒',
                                        content: '请确认授权，否则无法使用存入功能',
                                        success: function (tip) {
                                            if (tip.confirm) {
                                                wx.openSetting()
                                            }
                                        }
                                    })
                                }
                            })
                        }
                    });
                }
                this.setData({
                    focus: true
                })
            },
            fail: res => {
                console.log('用户拒绝了隐私协议')
            }
        })
    },
    // 动态播放视频
    playVideo_pust(e) {
        const index = e.currentTarget.dataset.index;
        const news = this.data.news.map((item, idx) => {
            if (idx === index) {
                item.itars_trfalse = true;
            } else {
                item.itars_trfalse = false;
            }
            return item;
        });
        this.setData({
            news: news
        });
    },
    videoEnded() {
        this.setData({
            itars_trfalse: false
        })
    },
    // 介绍播放视频
    playVideo(e) {
        let index = e.currentTarget.dataset.index
        let videovar = this.data.video_list[index].video_url
        this.setData({
            videoInfo: videovar
        })
        let flag = this.is_perfect();
        if (!flag) {
            return false;
        }
        this.setData({
            showTosting: true
        })
        // const index = e.currentTarget.dataset.index;
        // const video_list = this.data.video_list.map((item, idx) => {
        //   console.log('resvideo',video_list);
        //   if (idx === index) {
        //     item.isVideoPlaying = false;
        //   } else {
        //     item.isVideoPlaying = false;
        //   }
        //   return item;
        // });
        // this.setData({
        //   video_list: video_list
        // });
    },
    videoEnded() {
        this.setData({
            isVideoPlaying: false
        })
    },

    // DPF文件
    url_pdfar(e) {
        let flag = this.is_perfect();
        if (!flag) {
            return false;
        }
        var earIndex = e.currentTarget.dataset.index
        let id = this.data.manual[earIndex].id
        let url = this.data.manual[earIndex].testUrl
        if (!this.data.user_login) {
            wx.showToast({
                title: '登录后查看',
            })
            // return;
        }
        // 未完善信息
        // if (this.data.lo_gin == 0) {
        // 	wx.navigateTo({
        // 		url: '/pages/handbook/handbook?id=' + id,
        // 	})
        // } else {

        wx.showLoading({
            title: '打开中...',
            mask: true,
        })
        if (this.data.opening) {
            return;
        }
        this.setData({
            opening: true,
        })
        wx.downloadFile({
            url: url,
            success: (res) => {
                console.log('res.tempFilePath', res)
                if (res.statusCode === 200) {
                    wx.getFileInfo({
                        filePath: res.tempFilePath,
                        success: (fileRes) => {
                            var fileSizeBytes = fileRes.size;
                            var fileSizeMB = (fileSizeBytes / 1024 / 1024).toFixed(2);
                            var fileName = res.tempFilePath.substring(res.tempFilePath.lastIndexOf('/') + 1);
                            wx.openDocument({
                                showMenu: true,
                                filePath: res.tempFilePath,
                                fileType: 'pdf',
                                success: (res) => {
                                    console.log('详情', res);
                                }
                            })
                            this.setData({
                                opening: false,
                            })
                        },
                        fail: (fileRes) => {
                            this.setData({
                                opening: false,
                            })
                            console.error('获取文件失败', fileRes);
                        }
                    });
                } else {
                    this.setData({
                        opening: false,
                    })
                    console.error('下载失败:', res);
                }
                wx.hideLoading();
            },
            fail: (err) => {
                console.log(err)
                wx.hideLoading();
                this.setData({
                    opening: false,
                })
            }
        })
        // }
    },
    // 申请试用
    sqsy() {
        wx.navigateTo({
            url: '/pages/sqsy/sqsy',
        })
    },
    // 企业介绍
    enterpise() {
        let flag = this.is_perfect();
        if (!flag) {
            return false;
        }
        wx.navigateTo({
            url: '/pages/indexurl/indexurl',
        })
    },
    add_view_times(id) {
        var url = 'index/news_view'
        getApp().util.request({
            url: url,
            data: {
                id: id
            }
        }).then((res) => {

        })
    },
    // 动态详情
    ynamic(e) {
        let id = e.currentTarget.dataset.id;
        let link = e.currentTarget.dataset.link;

        //阅读次数+1
        this.add_view_times(id);
        if (link) {
            let url = link;
            wx.navigateTo({
                url: '/pages/progress/index?url=' + url,
            })
        } else {
            wx.navigateTo({
                url: '/pages/ynamic/index?id=' + id,
            })
        }
    },
    // 检索
    onshowar() {
        this.setData({ show: false })
    },
    onSelectatr() {
        this.setData({ show: true })
    },
    onClose() {
        this.setData({ show: false });
    },

    to_web(e) {
        console.log("跳转");
        let index = e.currentTarget.dataset.index;
        let url = this.data.product[index].url
        wx.navigateTo({
            url: '/pages/progress/index?url=' + url,
        })
    },

    onSelect(event) {
        console.log(event.detail);
        let cat_id = event.detail.id;
        this.setData({
            cat_id: cat_id,
            cat_name: event.detail.name
        })
        this.reset_prodect_data();
    },
    // 选项卡
    onChange(event) {
        let flag = this.is_perfect();
        if (!flag) {
            return false;
        }
        let index = event.detail.index;
        // 动态
        if (index == 0) {
            this.setData({
                activ_int: 0
            })
            this.init_video_info(0);
        }
        else if (index == 1) {
            this.setData({
                activ_int: 1
            })
            this.reset_news_data();
        }
        // 热点
        else if (index == 2) {
            this.setData({
                activ_int: 1
            })
            this.init_video_info(1);
        } else if (index == 3) {
            this.setData({
                activ_int: 1
            })
            wx.navigateTo({
                url: '/pages/product/product',
            })
        }
    },
    onChangeKey(e) {
        this.setData({
            va_search: e.detail
        }, () => {
        })
    },
    onSearch(e) {
        this.reset_prodect_data();
    },
    reset_prodect_data() {
        //获取产品
        this.setData({
            product: []
        }, () => {
            var url = 'index/product_list'
            getApp().util.request({
                url: url,
                data: {
                    cat_id: this.data.cat_id,
                    key: this.data.va_search
                }
            }).then((res) => {
                this.setData({
                    product: res.product,
                })
            })
        })

    },
    reset_news_data() {
        let index = this.data.currentTab;

        this.setData({
            news: []
        }, () => {
            var url = 'index/news_list'
            getApp().util.request({
                url: url,
                data: {
                    // cat_id: this.data.news_cat[index].id,
                }
            }).then((res) => {
                this.setData({
                    news: res,
                })
            })
        })

    },
    switchTab: function (e) {
        const tab = e.currentTarget.dataset.tab;
        console.log(tab);
        this.setData({
            currentTab: parseInt(tab)
        }, () => {
            this.reset_news_data();
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            active: 0
        })
        //扫码进来获取分享人信息
        if (typeof (options.scene) != 'undefined') {
            let scene = decodeURIComponent(options.scene);
            //&是我们定义的参数链接方式
            let P_account_id = scene.split("&")[0];
            console.log(P_account_id);
            wx.setStorageSync('P_account_id', P_account_id);
            // this.setData({
            // 	id:P_account_id
            // })
        }
        if (typeof options.account_id != 'undefined') {
            let P_account_id = options.account_id;
            console.log(P_account_id);
            //通过分享点击进来的
            wx.setStorageSync('P_account_id', P_account_id);
            // this.setData({
            // 	id:P_account_id
            // })
        }

        this.init_data();

        this.setData({
            times_flag: true
        })
    },

    init_data() {
        this.init_compnay_info();
        this.init_video_info(0);
        this.init_brochure_info();
        this.init_prodect_cat();
        // this.init_news_cat();
    },

    init() {
        return new Promise(async (resolve, reject) => {
            let P_account_id = wx.getStorageSync('P_account_id');
            console.log(P_account_id);
            var user = await getApp().util.getOne(P_account_id);

            this.setData({
                // user_login: user.user_login,
            }, () => {
                if (user.userInfo.avatar == '') {
                    user.userInfo.avatar = '/pages/image/no_img.png';
                }

                this.setData({
                    'personal.id': user.userInfo.id,
                    'personal.img_url': user.userInfo.avatar,
                    'personal.name': user.userInfo.username,
                    'personal.career': user.userInfo.position,
                    'personal.phone': user.userInfo.mobile,
                    'personal.email': user.userInfo.email,
                    'personal.addres': user.userInfo.company_address,
                    'personal.is_self': user.userInfo.is_self,
                }, () => {
                    // 观看人次数+1  不是自己看自己
                    if (this.data.times_flag && !this.data.personal.is_self) {
                        this.add_see_times();
                    }
                    this.setData({
                        times_flag: false
                    });
                    //我的访客记录
                    if (this.data.personal.is_self) {
                        this.init_visitor();
                    }
                    resolve();
                })
            })
        })
    },

    // 获取简介背景图 首页宣传视频 公司地址 网址 微信公众号二维码
    init_compnay_info() {
        //获取主营业务
        var url = 'index/compnay_info'
        getApp().util.request({
            url: url,
        }).then((res) => {
            this.setData({
                brief: res,
            })
        })
    },

    // 宣传视频
    init_video_info(type) {
        this.setData({
            video_list: [],
        })
        //获取主营业务
        var url = 'index/video_info'
        getApp().util.request({
            url: url,
            data: {
                type: type,
            }
        }).then((res) => {
            console.log(res);
            this.setData({
                video_list: res.video,
            })
        })
    },

    // 宣传手册
    init_brochure_info() {
        //获取主营业务
        var url = 'index/brochure_info'
        getApp().util.request({
            url: url,
        }).then((res) => {
            console.log('565', res);
            this.setData({
                manual: res.manual,
            })
        })
    },
    // 产品分类
    init_prodect_cat() {
        var url = 'index/prodect_cat'
        getApp().util.request({
            url: url,
        }).then((res) => {
            this.setData({
                actions: res.category,
                cat_id: typeof res.category[0] != 'undefined' ? res.category[0]['id'] : '',
                cat_name: typeof res.category[0] != 'undefined' ? res.category[0]['name'] : ''
            })
        })
    },
    init_news_cat() {
        var url = 'index/news_cat'
        getApp().util.request({
            url: url,
        }).then((res) => {
            this.setData({
                news_cat: res.category,
            })
        })
    },
    //访客记录
    init_visitor() {
        var url = 'visitor/visitor_home_info'
        getApp().util.request({
            url: url,
        }).then((res) => {

            this.setData({
                visitor: [
                    {
                        'num': res.user_cnt,
                        'itemList': res.accounts,
                    }
                ],
            })
        })
    },

    // 观看次数+1
    add_see_times() {
        // var url = 'user/see_times'
        // let user_id = this.data.personal.id
        // getApp().util.request({
        // 	url: url,
        // 	data: {
        // 		user_id: user_id
        // 	}
        // }).then((res) => {

        // })
    },
    // 分享次数+1
    add_share_times() {

        console.log(this.data.personal);
        var url = 'user/share_times'
        let user_id = this.data.personal.id
        getApp().util.request({
            url: url,
            data: {
                user_id: user_id
            }
        }).then((res) => {

        })
    },

    inputValue(e) {
        console.log(e);
    },

    // 立即授权
    getUserProfile() {
        var that = this;
        let avatarUrl = that.data.avatarUrl; //头像
        let nickName = that.data.nickName; //昵称
        console.log(avatarUrl)
        if (avatarUrl == defaultAvatarUrl) {
            wx.showToast({
                title: '请上传头像',
                icon: 'none',
                mask: false,
            });
            return false;
        } else if (nickName == '') {
            wx.showToast({
                title: '请填写昵称',
                icon: 'none',
                mask: false,
            });
            return false;
        }
        let params = {
            headimg: avatarUrl,
            nickname: nickName,
        };
        this.setData({
            show_disable: true
        })
        wx.login({
            //成功放回
            success: (res) => {
                let code = res.code
                params.code = code;
                getApp().util.request({
                    url: 'user/wxlogin',
                    data: params,
                }).then(function (res) {
                    wx.setStorageSync('token', res.data)
                    that.setData({
                        showtos: false,
                    })
                    that.init().then(async (res) => {
                        // 获取用户登录状态
                        var login_user = await getApp().util.getUser();
                        that.setData({
                            show_disable: false,
                            user_login: login_user.user_login,
                            lo_gin: login_user.user_login ? login_user.userInfo.perfect : 0
                        })
                    });
                    // wx.switchTab({
                    //   url: '/pages/my/my',
                    // })
                })
                that.setData({
                    disabled: true
                })
            },
            error: (res) => {
                console.log(res);
                that.setData({
                    disabled: false,
                })
            }
        });
    },

    onInput(e) {
        // let that = this;
        // var userInfot = {
        //     // name: this.data.name,
        //     telephone:this.data.telephone,
        //     // company: this.data.company,
        //     // duties: this.data.duties,
        // };
        // // if (this.data.name == '' || this.data.company == '') {
        // if (this.data.telephone == '') {
        //     wx.showToast({
        //         title: '请授权手机号',
        //         icon: 'none'
        //     })
        // } else {
        //     this.setData({
        //         input_disable: true,
        //     })
        //     let params = {
        //         // headimg: userInfot.avatarUrl,
        //         // username: userInfot.name,
        //         mobile: userInfot.telephone,
        //         // company: userInfot.company,
        //         // position: userInfot.duties,
        //     };
        //     getApp().util.request({
        //         url: 'user/perfect',
        //         data: params,
        //     }).then(function (res) {
        //         that.setData({
        //             showTostat: false,
        //             input_disable: false,
        //             lo_gin: 1,
        //         })
        //     })

            
        // }

        // console.log(userInfot);

        var that = this;
        let avatarUrl = that.data.avatarUrl; //头像
        let nickName = that.data.nickName; //昵称
        let telephone = this.data.telephone;
        console.log(avatarUrl)
        if (telephone == '') {
            wx.showToast({
                title: '请授权手机号',
                icon: 'none',
                mask: false,
            });
            return false;
        } 
        let params = {
            mobile: telephone,
        };
        this.setData({
            show_disable: true
        })
        wx.login({
            //成功放回
            success: (res) => {
                let code = res.code
                params.code = code;
                getApp().util.request({
                    url: 'user/wxlogin2',
                    data: params,
                }).then(function (res) {
                    wx.setStorageSync('token', res.data)
                    that.setData({
                        showTostat: false,
                    })
                    that.init().then(async (res) => {
                        // 获取用户登录状态
                        var login_user = await getApp().util.getUser();
                        that.setData({
                            show_disable: false,
                            user_login: login_user.user_login,
                            lo_gin: login_user.user_login ? login_user.userInfo.perfect : 0
                        })
                    });
                    // wx.switchTab({
                    //   url: '/pages/my/my',
                    // })
                })
                that.setData({
                    disabled: true
                })
            },
            error: (res) => {
                console.log(res);
                that.setData({
                    disabled: false,
                })
            }
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        tabbar.switchTab(this, 0); //tabIndex是当前tab的索引
        this.init().then(async (res) => {
            // 获取用户登录状态
            var login_user = await getApp().util.getUser();
            this.setData({
                user_login: login_user.user_login,
                showtos: login_user.user_login ? false : true,
                lo_gin: login_user.user_login ? login_user.userInfo.perfect : 0
            })
        });
    },

    is_perfect() {
        // 未完善信息
        if (this.data.lo_gin == 0) {
            this.setData({
                showTostat: true,
            })
            return false;
            throw new Error("未完善信息");
        }
        return true;
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        const videoList = this.data.video_list.map((item) => {
            item.isVideoPlaying = false;
            return item;
        });
        this.setData({
            video_list: videoList
        });
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        var that = this;
        var account_id = this.data.personal.id
        console.log('onShareAppMessage' + account_id);
        var link_path = "/pages/index/index?account_id=" + account_id;
        // 自己点自己不算
        if (!this.data.personal.is_self) {
            this.add_share_times();
        }
        return {
            // title: share_title,
            path: link_path,
            // imageUrl: share_image, //自定义分享图（750*600【5:4】）
        }
    }
})